package it.uniroma2.controller;

import it.uniroma2.MonitorClient;
import it.uniroma2.cloud.PROVIDER;
import it.uniroma2.monitor.client.DateUtils;
import it.uniroma2.monitor.client.MetricRequest;
import it.uniroma2.monitor.client.MetricResult;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

public class LatencyChecker {

	private MonitorClient monitorClient;

	public LatencyChecker() {
		this.monitorClient = MonitorClient.getInstance();
		Timer timer = new Timer();
		timer.scheduleAtFixedRate(new LatencyCheck(), 0L, // initial delay
			10 * 1000);
	}

	class LatencyCheck extends TimerTask {

		public void run() {
			System.out.println("-- Latency Check: " + new Date());
			new Thread(new LatencyCheckExecutor(PROVIDER.AWS_EC2)).start();
			new Thread(new LatencyCheckExecutor(PROVIDER.OPENSTACK)).start();

		}
	}

	class LatencyCheckExecutor implements Runnable {

		private PROVIDER provider;

		public LatencyCheckExecutor(PROVIDER provider) {
			this.provider = provider;
		}

		@Override
		public void run() {
			DateTime until = new DateTime(DateTimeZone.UTC);
			DateTime from = DateUtils.lastMinutes(until, 3);
			
			MetricRequest reqClientDuration = new MetricRequest(
					"*.client.duration.mean",
					from, until);
			MetricResult resultClientDuration = monitorClient.makeRequest(reqClientDuration);
			System.out.println("*.client.duration.mean[AVG on " +resultClientDuration.size()+ " results: " + resultClientDuration.avg());
			
			MetricRequest reqProcessing = new MetricRequest(
					"post.aggregated."+ provider.name() +".imagetranscoder.processing-duration.mean",
					from, until);
			MetricResult resultProcessing = monitorClient.makeRequest(reqProcessing);
			System.out.println("post.aggregated."+ provider.name() +".imagetranscoder.processing-duration.mean [AVG on " +resultProcessing.size()+ " results: " + resultProcessing.avg());
			double latency = resultClientDuration.avg() - resultProcessing.avg();
			ReporterChecker.getInstance().setLatencyMean(provider, latency);
			System.out.println("Latency on " + provider + ": " +  latency + " ms");
		}
	}

	public static void main(String[] args) {
		new LatencyChecker();
	}
}
